import { createStore } from 'vuex'
import getters from './getters'
const store = createStore({
  state: {
    userInfo: uni.getStorageSync('userInfo') || null,
    token: uni.getStorageSync('token') || null,
    isLogin: uni.getStorageSync('isLogin') || false,
    connectedDevice: null,
    deviceList: [],
    isBluetoothEnabled: false
  },

  mutations: {
    SET_USER_INFO(state, userInfo) {
      state.userInfo = userInfo
      uni.setStorageSync('userInfo', userInfo)
    },

    SET_TOKEN(state, token) {
      state.token = token
      uni.setStorageSync('token', token)
    },

    LOGIN(state, { userInfo, token }) {
      state.userInfo = userInfo
      state.token = token
      state.isLogin = true
      uni.setStorageSync('userInfo', userInfo)
      uni.setStorageSync('token', token)
      uni.setStorageSync('isLogin', true)
    },

    LOGOUT(state) {
      state.userInfo = null
      state.token = null
      state.isLogin = false
      uni.removeStorageSync('userInfo')
      uni.removeStorageSync('token')
      uni.removeStorageSync('isLogin')
    },

    SET_CONNECTED_DEVICE(state, device) {
      state.connectedDevice = device
    },

    ADD_DEVICE(state, device) {
      const index = state.deviceList.findIndex(d => d.deviceId === device.deviceId)
      if (index > -1) {
        state.deviceList[index] = device
      } else {
        state.deviceList.push(device)
      }
    },

    REMOVE_DEVICE(state, deviceId) {
      state.deviceList = state.deviceList.filter(d => d.deviceId !== deviceId)
    },

    SET_BLUETOOTH_STATUS(state, enabled) {
      state.isBluetoothEnabled = enabled
    }
  },

  actions: {
    login({ commit }, { userInfo, token }) {
      commit('LOGIN', { userInfo, token })
    },

    logout({ commit }) {
      commit('LOGOUT')
    },

    setUserInfo({ commit }, userInfo) {
      commit('SET_USER_INFO', userInfo)
    },

    setToken({ commit }, token) {
      commit('SET_TOKEN', token)
    },

    setConnectedDevice({ commit }, device) {
      commit('SET_CONNECTED_DEVICE', device)
    },

    addDevice({ commit }, device) {
      commit('ADD_DEVICE', device)
    },

    removeDevice({ commit }, deviceId) {
      commit('REMOVE_DEVICE', deviceId)
    },

    setBluetoothStatus({ commit }, enabled) {
      commit('SET_BLUETOOTH_STATUS', enabled)
    }
  },
  getters
})

export default store
